package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"

	"fancy_web/data"
)

type Config struct {
	Address      string
	ReadTimeout  int64
	WriteTimeout int64
	Static       string
}

var config Config
var logger *log.Logger
var userMgr data.UserMgr

func init() {
	loadConfig()
	file, err := os.OpenFile("chitchat.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("failed to open log file", err)
	}
	logger = log.New(file, "INFO ", log.Ldate|log.Ltime|log.Lshortfile)
	userMgr = data.NewUserMgr()
	var dbUsers []data.DbUser
	data.Gorm.Find(&dbUsers)
	for _, v := range dbUsers {
		u := data.User{
			Id:    v.ID,
			Uuid:  v.Uuid,
			Name:  v.Name,
			Email: v.Email,
			Pswd:  v.Pswd,
		}
		setUser(u.Id, &u)
	}
}

func loadConfig() {
	file, err := os.Open("config.json")
	if err != nil {
		log.Fatalln("can not open config file", err)
	}
	decoder := json.NewDecoder(file)
	config = Config{}
	err = decoder.Decode(&config)
	if err != nil {
		log.Fatalln("can not get config from file", err)
	}
}

func p(a ...interface{}) {
	fmt.Println(a)
}

func version() string {
	return "0.1"
}

func generateHTML(w http.ResponseWriter, data interface{}, filenames ...string) {
	var files []string
	for _, file := range filenames {
		files = append(files, fmt.Sprintf("templates/%s.html", file))
	}
	templates := template.Must(template.ParseFiles(files...))
	templates.ExecuteTemplate(w, "layout", data)
}

func session(w http.ResponseWriter, r *http.Request) (sess data.Session, err error) {
	cookie, err := r.Cookie("_cookie")
	fmt.Println("session", err, cookie)
	if err == nil {
		sess = data.Session{
			Uuid: cookie.Value,
		}
		if ok, _ := sess.Check(); !ok {
			err = errors.New("invalid session")
		}
	}
	return
}

func parseTemplateFiles(filenames ...string) (t *template.Template) {
	var files []string
	t = template.New("layout")
	for _, file := range filenames {
		files = append(files, fmt.Sprintf("templates/%s.html", file))
	}
	t = template.Must(t.ParseFiles(files...))
	return
}

func getUser(id uint) *data.User {
	return userMgr.GetUser(id)
}

func setUser(id uint, user *data.User) {
	userMgr.SetUser(id, user)
}
